<template>
  <div class="main-todo">
    <input
      type="text"
      class="add-todo"
      placeholder="what to do?"
      autofocus
      @keyup.enter="addToDo"
      v-model="content"
    />
    <todo-item
      v-for="(item, index) in filterData"
      :key="index"
      :todo="item"
      @del="handleDeleteItem"
    ></todo-item>
    <todo-info
      :total="total"
      @toggleState="handleToggleState"
      @clearCompleted="handleClear"
    ></todo-info>
  </div>
</template>

<script>
import TodoItem from "./coms/TodoItem.vue";
import TodoInfo from "./coms/TodoInfo.vue";

let id = 2;
export default {
  name: "MainToDo",
  data() {
    return {
      todoData: [
        {
          id: 0,
          content: "test",
          compledted: false,
        },
        {
          id: 1,
          content: "test2",
          compledted: false,
        },
      ],
      content: "",
      total: 2,
      filter: "all",
    };
  },
  methods: {
    addToDo() {
      if (this.content === "") return;

      this.todoData.unshift({
        id: id++,
        content: this.content,
        compledted: false,
      });
      this.content = "";
    },
    handleDeleteItem(id) {
      this.todoData.splice(
        this.todoData.findIndex((item) => item.id === id),
        1
      );
    },
    handleToggleState(state) {
      this.filter = state;
    },
    handleClear() {
      this.todoData = this.todoData.filter((item) => !item.compledted);
    },
  },
  watch: {
    todoData: {
      deep: true,
      handler() {
        this.total = this.todoData.filter((item) => !item.compledted).length;
      },
    },
  },
  computed: {
    filterData() {
      switch (this.filter) {
        case "active":
          return this.todoData.filter((item) => !item.compledted);
          break;
        case "completed":
          return this.todoData.filter((item) => item.compledted);
          break;
        case "all":
        default:
          return this.todoData;
      }
    },
  },
  components: {
    TodoItem: TodoItem,
    TodoInfo: TodoInfo,
  },
};
</script>

<style lang="stylus" scoped>
.main-todo {
  margin: 0 auto;
  width: 600px;
  background-color: #ffffff;
  box-shadow: 0 0 5px #666;

  .add-todo {
    padding: 16px 16px 16px 36px;
    width: 100%;
    font-size: 24px;
    font-family: inherit;
    font-weight: inherit;
    color: inherit;
    border: none;
    outline: none;
    box-sizing: border-box;
  }
}
</style>